#include "Stdafx.h"
#include "SkyPlane.h"

namespace Pulpy
{

	SkyPlane::SkyPlane(int slices, float radius, float height, float hTile, float vTile, char * texture): _RenderMesh(false),_Vertices(NULL),_Indices(NULL), _Top(800.0f), _Scale(0.5f)
	{
		if(LoadTGA(&_Image, texture))
			Logger::getInstance().addLog("SkyPlane::Loaded Texture: ",false);
		else
			Logger::getInstance().addLog("SkyPlane::Fail to load Texture: ",false);
		Logger::getInstance().addLog(texture);
		if (_Vertices) { delete [] _Vertices; _Vertices = 0; } 
		if (_Indices) { delete [] _Indices; _Indices = 0; } 	
		(slices < 1) ? (slices = 1) : (slices > 256) ? (slices = 256) : (slices); 
		_NumVertices = ( slices + 1 ) * ( slices + 1 ); 
		_NumIndices = slices * slices * 2 * 3; 
		_Vertices = new Vertex[_NumVertices]; 
		_Indices = new unsigned short[_NumIndices]; 
		float planeSize = 2.0f * sqrtf((height*height) - (radius*radius)); 
		float delta = planeSize / (float)slices; 
		float texDelta = 2.0f / (float)slices;
		for ( int z = 0; z <= slices; ++z )
		{
			for ( int x = 0; x <= slices; ++x )
			{
				float xDist = (-0.5f * planeSize) + ( (float)x * delta );
				float zDist = (-0.5f * planeSize) + ( (float)z * delta );
				float xHeight = ( xDist * xDist ) / height;
				float zHeight = ( zDist * zDist ) / height;
				float height = xHeight + zHeight;
				Vertex vertex;
				vertex.x = xDist;
				vertex.y = -height;
				vertex.z = zDist;
				// Calculate the texture coordinates
				vertex.u = hTile * ((float)x * texDelta * 0.5f);
				vertex.v = vTile * (1.0f - (float)z * texDelta * 0.5f);
				_Vertices[z * (slices+1) + x] = vertex;
			}
		}
		int index = 0; // Indices 
		for (int i=0; i < slices; ++i) 
		{ 
			for (int j=0; j < slices; ++j) 
			{ 
				int startvert = (i * (slices+1) + j); 
				_Indices[index++] = startvert;// tri 1 
				_Indices[index++] = startvert + 1; 
				_Indices[index++] = startvert + slices + 1; 
				_Indices[index++] = startvert + 1; // tri 2 
				_Indices[index++] = startvert + slices + 2; 
				_Indices[index++] = startvert + slices + 1; 
			} 
		}
	}

	void SkyPlane::draw()
	{
		if(_RenderMesh)
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		else
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
		glDisable(GL_CULL_FACE);
		glEnable(GL_TEXTURE_2D);
		glPushMatrix(); 
			glLoadIdentity();
			glTranslatef( 0.0f, _Top, 0.0f ); 
			glScalef( _Scale, _Scale, _Scale );
			glColor3f(1,1,1);
			glBindTexture(GL_TEXTURE_2D, _Image.texID); 
			glBegin(GL_TRIANGLES); 
			for (int i=0; i < _NumIndices; ++i) { 
				glColor3f(1.0f, 1.0f, 1.0f); 
				unsigned short index = _Indices[i]; 
				glTexCoord2f(_Vertices[index].u, _Vertices[index].v); 
				glVertex3f(_Vertices[index].x, _Vertices[index].y, _Vertices[index].z); 
			} 
			glEnd(); 
		glPopMatrix();
		glDisable(GL_TEXTURE_2D);
		glEnable(GL_CULL_FACE);
	}
}